package com.cntv.viewmodeldemo.onlyviewmodel;

import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.cntv.viewmodeldemo.R;

/**
 * Created By Mahongyin
 * Date    2020/9/17 14:53
 * ViewModel使用
 */
public class ViewModelActivity extends AppCompatActivity {
    MyViewModel viewModel;
    TextView textView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewmodel);
        textView = findViewById(R.id.textView);

        viewModel = new ViewModelProvider(this).get(MyViewModel.class);
//vm生命周期比activity长 当activity重建能保障数据不丢失
//如果不使用vm 当翻转屏幕/切换系统语言 数据会丢失. 而把数据交给vm  当activity重建时从vm取数据即可。
        textView.setText(String.valueOf(viewModel.getNum()));

        findViewById(R.id.button).setOnClickListener(v -> {
            viewModel.add(1);
            textView.setText(String.valueOf(viewModel.getNum()));
        });
        findViewById(R.id.button2).setOnClickListener(v -> {
            viewModel.add(-1);
            textView.setText(String.valueOf(viewModel.getNum()));
        });
    }
}
